<?php

namespace Plugin;

use W3\Widget;
use W3\Plugin;

/**
 * 插件列表组件
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Rows extends Widget
{
    /**
     * 已启用插件
     *
     * @access public
     * @var array
     */
    public $activatedPlugins = [];
	
    /**
     * 初始化
     *
     * @access protected
     * @return void
     */
    protected function init()
    {
		# 定义变量默认数据
        $this->parameter([
		
		    'activated' => NULL
			
		], true);
    }

    /**
     * @return array
     */
    protected function getPlugins()
    {
        return glob(W3_PLUGIN_DIR . '*');
    }

    /**
     * 执行函数
     *
     * @access public
     * @return void
     */
    public function execute()
    {
        /** 列出插件目录 */
        $pluginDirs = $this->getPlugins();

        /** 获取已启用插件 */
        $this->activatedPlugins = Plugin::export();

        if (!empty($pluginDirs)) {
            foreach ($pluginDirs as $pluginDir) 
			{
                if (!is_dir($pluginDir)) {
                    continue;
                }

                /** 获取插件名称 */
                $pluginName = basename($pluginDir);

                /** 获取插件主文件 */
                $pluginFile = Plugin::getFile($pluginName);

                if (file_exists($pluginFile)) {
                    $info = Plugin::getInfo($pluginFile);

                    $info['name'] = $pluginName;
                    $info['dependence'] = Plugin::version($this->config->version, $info['dependence']);

                    /** 默认即插即用 */
                    $info['activated'] = 0;

                    if (isset($info['activate']) || isset($info['deactivate']) || isset($info['config'])) {
                        $info['activated'] = isset($this->activatedPlugins[$pluginName]);

                        if ($info['activated']) {
                            unset($this->activatedPlugins[$pluginName]);
                        }
                    }

                    if ($info['activated']  == $this->parameter->activated) {
                        $this->push($info);
                    }
                }
            }
        }
    }
}
